<?php
declare(strict_types=1);
namespace App\Game\Server;

use App\Service\ChatService;
use App\Service\GameService;
use App\Service\RoomService;
use App\Service\UserService;
use Closure;
use Hyperf\Contract\StdoutLoggerInterface;
use Swoole\WebSocket\Server;
use Hyperf\Di\Annotation\Inject;

/**
 * 大厅服务逻辑处理
 * Class HallServer
 * @package App\Game
 */

class GameServer
{
    /**
     * 依赖注入 日志服务
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $console;

    /**
     * 开始游戏
     * @param Closure $next
     * @param Server $server
     * @param array $params
     * @return mixed
     */
    public function startGame(Closure $next, Server $server, array $params)
    {
        //验证状态
        $user = UserService::getUserByFd($params['fd'], $server);
        if (!$user) {
            return $next(error('请先登录'));
        }
        //检查房间
        $room_id = $user['room_id'] ?? 0;
        if (!$room_id) {
            return $next(error('不在房间内'));
        }
        $room = RoomService::getRoom($room_id);
        if (!$room) {
            return $next(error('房间不存在'));
        }
        //检查是否是房主
        if ($room['owner'] != $user['uid']) {
            return $next(error('只有房主才能开始游戏'));
        }
        //检查是否开始游戏
        if (isset($room['game_start']) && $room['game_start'] > 0) {
            return $next(error('已经在游戏中'));
        }
        //检查玩家是否准备
        for ($i = 1; $i <= 4; $i++) {
            if ($i == $user['table']) {
                continue;
            }
            if (!isset($room['table'.$i.'_ready']) || !$room['table'.$i.'_ready']) {
                return $next(error('有玩家未准备'));
            }
        }
        //修改状态
        for($i = 1; $i <= 4; $i++) {
            UserService::updateUserRedis($room['table'.$i], ['game_start' => 1]);
        }
        RoomService::updateRoom($room_id, ['game_start' => 1]);
        //通知客户端开始游戏
        ChatService::msgToRoom('startGame', $room_id, $server, 0, 'game_start');
        $this->console->info($room_id.'开始游戏');
        $this->initGameData($room_id);
        return $next(success());
    }

    /**
     * 摸牌
     */
    public function getCards()
    {

    }

    /**
     * 初始化游戏
     * @param $room_id
     */
    private function initGameData($room_id)
    {
        $cards = GameService::shuffleCards();
        //设置卡池
        GameService::setCardPool($cards, $room_id);
    }
}